﻿using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Modularity;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Composite.Wpf.Events;
using Microsoft.Practices.Unity;
using WpfTwitterClient.Infrastructure;
using WpfTwitterClient.Infrastructure.Events;
using WpfTwitterClient.Infrastructure.Models;
using WpfTwitterClient.Modules.Timelines.Views.HomeTimeline;

namespace WpfTwitterClient.Modules.Timelines
{
    public class TimelinesModule : IModule
    {
        private readonly IUnityContainer container;
        private readonly IRegionManager regionManager;
        private IHomeTimelinePresenter presenter;
        private IEventAggregator eventAggregator;
        private IRegion mainRegion;

        public TimelinesModule(IUnityContainer container, IRegionManager regionManager, IEventAggregator eventAggregator)
        {
            this.container = container;
            this.regionManager = regionManager;
            this.eventAggregator = eventAggregator;
        }

        public void Initialize()
        {
            eventAggregator.GetEvent<LoadingTweetsEvent>().Subscribe(LoadingTweetsEventHandler, ThreadOption.UIThread);
            eventAggregator.GetEvent<LoadedTweetsEvent>().Subscribe(LoadedTweetsEventHandler, ThreadOption.UIThread, true);
            this.RegisterViewsAndServices();

            presenter = container.Resolve<IHomeTimelinePresenter>();

            mainRegion = this.regionManager.Regions[RegionNames.MainRegion];
            mainRegion.Add(presenter.View, "HomeTimelineView");
        }

        private void LoadingTweetsEventHandler(string str)
        {
            mainRegion.Activate(presenter.View);
        }

        private void LoadedTweetsEventHandler(Tweets tweets)
        {
            mainRegion.Activate(presenter.View);
        }

        protected void RegisterViewsAndServices()
        {
            this.container.RegisterType<IHomeTimelinePresenter, HomeTimelinePresenter>(new ContainerControlledLifetimeManager());
            this.container.RegisterType<IHomeTimelineView, HomeTimelineView>(new ContainerControlledLifetimeManager());
        }
    }
}
